<?php
if(!defined('IN_DISCUZ')) exit('Access Denied');

global $_G;
$uid = $_G['uid'];
// if(!$uid) {
//     $data = [
//         'success' => false,
//         'message' => '请先登录'
//     ];
//     echo json_encode($data);
//     exit;
// }

$configs = C::t('#erling_filedset#er_filedset_config')->fetch_by_keys([
    'path_before', 'allowed_groups', 'max_size', 'file_types', 'file_num'
]);
$formhash = FORMHASH;

$configs = array_map(function($item) {
    return is_array($item) && isset($item['value']) ? $item['value'] : $item;
}, $configs);
// $configs['path_before'] = $configs['path_before']? $configs['path_before'] : $_G['siteurl'].'source/plugin/erling_filedset';
$configs = array_map(function($item) {
    return is_array($item) && isset($item['value']) ? $item['value'] : $item;
}, $configs);

// 处理path_before的值（可能是JSON字符串或数组）
$path_before = $configs['path_before'];
if(is_string($path_before) && $path_before[0] === '[') {
    $path_before = json_decode($path_before, true);
}

if(is_array($path_before)) {
    $non_empty_values = array_filter($path_before, function($v) { 
        return $v !== '' && $v !== null; 
    });
    if(empty($non_empty_values)) {
        $configs['path_before'] = $_G['siteurl'].'source/plugin/erling_filedset';
    } else {
        $configs['path_before'] = $path_before;
    }
} elseif(empty($path_before)) {
    $configs['path_before'] = $_G['siteurl'].'source/plugin/erling_filedset';
}

$er_filedset = C::t('#erling_filedset#er_filedset');
$page = $_GET['page']? intval($_GET['page']) : 1;
$pagesize = 15;

if(!empty($uid)) {
    $er_filedset_data = $er_filedset->fetch_query($page, $pagesize, ['uid' => $uid]);
} else {
    $er_filedset_data = [];
}


// 判断是否上传覆盖
$is_upload_cover = false;
$cover_file_info = [];
if(isset($_GET['file_id']) && $_GET['file_id']) {
    $file_id = intval($_GET['file_id']);
    $cover_file_info = $er_filedset->fetch_by_id($file_id);
    if($cover_file_info && $cover_file_info['uid'] == $uid) {
        $is_upload_cover = true;
    } else {
        $is_upload_cover = false;
     }
}

$template_name = defined('IN_MOBILE') && IN_MOBILE ? 'erling_filedset:touch/upload_form' : 'erling_filedset:upload_form';
include template($template_name, $template_data);